<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="450px" :title="`${drawerProps.title}规格`">
    <el-form
      ref="ruleFormRef"
      label-width="100px"
      label-suffix=" :"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="drawerProps.row"
      :hide-required-asterisk="drawerProps.isView"
    >
      <el-form-item label="规格名" prop="goodName">
        <el-input v-model="drawerProps.row!.name" placeholder="请填写规格名" clearable></el-input>
      </el-form-item>
      <el-form-item label="--规格值--" prop="specValue">
        <div
          v-for="(item, index) in drawerProps.row!.specOptions"
          :key="index"
          class="flx-justify-between"
          style="margin-bottom: 1em"
        >
          <el-input v-model="item.name" placeholder="请填写规格值" clearable></el-input>
          <Delete style="width: 1.2em; height: 1.2em; margin-left: 8px; color: red" @click="deleteOne(index, item.id)" />
        </div>
      </el-form-item>
      <el-button type="primary" @click="addOne">+添加规格值</el-button>
    </el-form>
    <template #footer>
      <el-button @click="drawerVisible = false">取消</el-button>
      <el-button v-show="!drawerProps.isView" type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="SpecDrawer">
import { ref, reactive } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { Specifications } from "@/api/interface";

const rules = reactive({
  name: [{ required: true, message: "请填写规格名" }]
});

interface DrawerProps {
  title: string;
  isView: boolean;
  row: Partial<Specifications.ResSpecList>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {
    specOptions: []
  }
});

// 接收父组件传过来的参数
const acceptParams = (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;
};

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      console.log("drawerProps.value.row", drawerProps.value.row);
      let params = JSON.parse(JSON.stringify(drawerProps.value.row!));
      params.specOptions.forEach(item => {
        if (item.id) {
          if (!params.specOptionsUpdate) {
            params.specOptionsUpdate = [];
          }
          params.specOptionsUpdate.push(item);
        } else {
          if (!params.specOptionsAdd) {
            params.specOptionsAdd = [];
          }
          params.specOptionsAdd.push(item);
        }
      });
      if (deleteIds.length) {
        params.specOptionsDeleteIds = deleteIds;
      }
      delete params.specOptions;
      console.log("params", params);
      await drawerProps.value.api!(params);
      ElMessage.success({ message: `${drawerProps.value.title}规格成功！` });
      drawerProps.value.getTableList!();
      drawerVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};
const deleteIds: Array<Number> = [];
const deleteOne = (index: number, id) => {
  if (id) {
    deleteIds.push(id);
  }
  drawerProps.value.row!.specOptions?.splice(index, 1);
};
const addOne = () => {
  console.log(drawerProps.value.row, "drawerProps.value.row");
  if (drawerProps.value.row!.specOptions && drawerProps.value.row!.specOptions.length >= 20) {
    return ElMessage.warning({ message: "最多添加20个规格值" });
  }
  if (drawerProps.value.row!.specOptions && drawerProps.value.row!.specOptions.some(v => v.name === ""))
    return ElMessage.warning({ message: "请先填写规格值" });
  drawerProps.value.row!.specOptions?.push({ name: "" });
};
defineExpose({
  acceptParams
});
</script>
